import React, { useContext, useEffect, useState } from 'react';
import {
  Button,
  Form,
  Grid,
  Input,
  InputNumber,
  Message,
  Modal,
  Select,
  Space,
} from '@arco-design/web-react';
import useLocale from '@/utils/useLocale';
import locale from './locale';
import { GlobalContext } from '@/context';
import { EntityCreate } from '@/api/interface/entity';
import styles from './style//index.module.less';
import { Emirates, Enums } from '@/api/modules/index';
import { EnumsRes } from '@/api/interface';
import { Create, Update } from '@/api/modules/entity';
import AppUpload from '@/components/AppUpload';
import {
  IconCheck,
  IconClose,
  IconDelete,
  IconEdit,
  IconFile,
  IconToBottom,
  IconUpload,
} from '@arco-design/web-react/icon';
import cs from 'classnames';
import { usedownloadDoc } from '@/utils/useDownload';
import ModalTitle from '@/components/ModalTitle';
import cloneDeep from 'lodash/cloneDeep';

const Option = Select.Option;
const { Row, Col } = Grid;
const { useForm } = Form;
function CreateForm({
  record,
  visible,
  onVisible,
}: {
  record: EntityCreate;
  visible: boolean;
  onVisible: (status: boolean, refresh?: boolean) => void;
}) {
  const t = useLocale(locale);
  const { lang, rtl } = useContext(GlobalContext);
  const [form] = useForm();
  const [loading, setLoading] = useState(false);

  const [emirate, setEmirate] = useState<Array<EnumsRes>>([]);
  const [entityReferenceEnums, setEntityReferenceEnums] = useState<
    Array<EnumsRes>
  >([]);
  const getEnums = () => {
    Enums({ type: 'EntityReferenceEnums' }).then((res) => {
      setEntityReferenceEnums(res.data);
    });
  };

  const getEmirate = () => {
    Emirates()
      .then((res) => {
        setEmirate(res.data);
      })
      .catch((e) => {
        console.log(e);
      });
  };
  useEffect(() => {
    getEnums();
    getEmirate();
    setfFleList([]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible]);

  useEffect(() => {
    if (visible) {
      setLoading(false);
      if (record.id) {
        form.setFieldsValue({
          chairman: record.chairman,
          name: record.name,
          nameAr: record.nameAr,
          reference: (record.reference && record.reference?.key) || undefined,
          shareholdingPercentage: record.shareholdingPercentage,
          emirate: record.emirate && record.emirate?.key,
        });
        setfFleList(cloneDeep(record.attachments));
        return;
      }
      form.resetFields();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible]);

  const onCancel = () => {
    form.resetFields();
    onVisible(false);
  };

  const onCreate = () => {
    form.validate((errors, values) => {
      if (!errors) {
        const params = {
          ...values,
          attachments: fileList,
          id: record.id,
          active: record.active,
        };
        console.log(params);
        if (record.id) {
          setLoading(true);
          Update(params)
            .then(() => {
              onVisible(false, true);
              form.resetFields();
              setLoading(false);
              Message.success(t['update.success']);
            })
            .catch(() => {
              setLoading(false);
            });
          return;
        }
        setLoading(true);
        Create(params)
          .then(() => {
            onVisible(false, true);
            form.resetFields();
            setLoading(false);
            Message.success(t['create.success']);
          })
          .catch(() => {
            setLoading(false);
          });
      }
    });
  };

  const [fileList, setfFleList] = useState<any>([]);
  const onAdd = (e) => {
    const files = e.map((a) => ({
      desc: '',
      fileName: '',
      cacheName: '',
      href: a.href,
    }));
    setfFleList((a) => [...a, ...files]);
  };
  const onRemove = (href) => {
    const arr = fileList.filter((a) => a.href !== href);
    setfFleList(arr);
  };

  //开始编辑
  const onStart = (row) => {
    const arr = [...fileList];
    const index = arr.findIndex((a) => a.href === row.href);
    arr[index].edit = true;
    arr[index].cacheName = arr[index].fileName;
    setfFleList(arr);
  };

  //获取去文件后缀
  function getFileExtension(filename) {
    return filename.substring(filename.lastIndexOf('.') + 1);
  }

  const onEnd = (row) => {
    if (!row.fileName) {
      onFileCancel(row);
      return;
    }
    const name = getFileExtension(row.href);
    const arr = [...fileList];
    const index = arr.findIndex((a) => a.href === row.href);
    arr[index].edit = false;
    arr[index].fileName = `${row.fileName}.${name}`;
    setfFleList(arr);
  };

  const onFileCancel = (row) => {
    const arr = [...fileList];
    const index = arr.findIndex((a) => a.id === row.id);

    arr[index].fileName = arr[index].cacheName;
    arr[index].edit = false;
    setfFleList(arr);
  };

  const listItemEle = (a, edit = false) => {
    return (
      <>
        <div className={cs(styles['item-text'])}>
          <IconFile className={cs(styles['item-icon'])} />
          {a.edit && edit ? (
            <>
              <Input
                onPressEnter={(enevt) => {
                  enevt.stopPropagation();
                  onEnd(a);
                }}
                onChange={(e) => (a.fileName = e)}
                suffix={
                  <>
                    <IconCheck
                      onClick={(enevt) => {
                        enevt.stopPropagation();
                        onEnd(a);
                      }}
                      className={styles['item-icon-hover']}
                    />
                    <IconClose
                      onClick={(enevt) => {
                        enevt.stopPropagation();
                        onFileCancel(a);
                      }}
                      className={styles['item-icon-hover']}
                    />
                  </>
                }
              ></Input>
            </>
          ) : (
            <div
              className={cs(
                styles['item-span'],
                'ellipsis ltr',
                lang === 'en-US' ? '' : styles['item-span-rtl']
              )}
            >
              {a.fileName ? a.fileName : a.href}
            </div>
          )}
        </div>
        <div>
          <IconEdit
            className={styles['item-icon-hover']}
            onClick={(enevt) => {
              enevt.stopPropagation();
              onStart(a);
            }}
          />
          <IconDelete
            className={styles['item-icon-hover']}
            onClick={(e) => {
              onRemove(a.href);
              e.stopPropagation();
            }}
          />
          <IconToBottom className={styles['item-icon-hover']} />
        </div>
      </>
    );
  };

  return (
    <div>
      <Modal
        title={
          <ModalTitle
            title={record.id ? t['create.editTitile'] : t['create.title']}
          />
        }
        style={{ width: '786px' }}
        visible={visible}
        onCancel={() => onCancel()}
        maskClosable={false}
        unmountOnExit={true}
        footer={null}
        className={cs(rtl ? 'rtl' : '')}
      >
        <div>
          <Form
            form={form}
            labelAlign="left"
            labelCol={{ span: 9 }}
            wrapperCol={{ span: 15 }}
            // initialValues={formParams}
            validateMessages={{
              required: () => t['empty'],
            }}
            validateTrigger="onBlur"
            layout="vertical"
            autoComplete="off"
          >
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  label={t['create.nameEn']}
                  field="name"
                  rules={[{ required: true }]}
                >
                  <Input
                    allowClear
                    maxLength={100}
                    placeholder={t['create.nameEn.placeholder']}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={t['create.nameAr']}
                  field="nameAr"
                  rules={[{ required: true }]}
                >
                  <Input
                    allowClear
                    maxLength={100}
                    placeholder={t['create.nameAr.placeholder']}
                  />
                </Form.Item>
              </Col>

              <Col span={12}>
                <Form.Item
                  label={t['create.shareholdingPercentage']}
                  field="shareholdingPercentage"
                >
                  <InputNumber
                    placeholder={t['create.shareholdingPercentage.placeholder']}
                    min={0}
                    max={100}
                    hideControl
                    step={0.1}
                    precision={2}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label={t['create.reference']} field="reference">
                  <Select
                    allowClear
                    placeholder={t['create.reference.placeholder']}
                  >
                    {entityReferenceEnums.map((option, index) => (
                      <Option key={index} value={option.key}>
                        {option.value[lang === 'en-US' ? 'en' : 'ar']}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={t['create.emirate']}
                  field="emirate"
                  rules={[{ required: true }]}
                >
                  <Select
                    allowClear
                    placeholder={t['create.emirate.placeholder']}
                  >
                    {emirate.map((option, index) => (
                      <Option key={index} value={option.key}>
                        {option.value[lang === 'en-US' ? 'en' : 'ar']}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label={t['create.chairman']} field="chairman">
                  <Input
                    allowClear
                    maxLength={100}
                    placeholder={t['create.chairman.placeholder']}
                  />
                </Form.Item>
              </Col>
              <Col span={24} style={{ maxHeight: '50vh', overflow: 'auto' }}>
                <Form.Item label={t['create.Attachments']}>
                  <div className={styles['upload']}>
                    <div className={styles['list']}>
                      {fileList.map((a, k) => (
                        <div
                          key={k}
                          className={cs(
                            styles['item'],
                            'cursor-pointer',
                            lang === 'en-US' ? '' : styles['item-rtl']
                          )}
                          onClick={() => {
                            if (!a.edit) {
                              usedownloadDoc(a.href, a.fileName);
                            }
                          }}
                        >
                          {listItemEle(a, true)}
                        </div>
                      ))}
                    </div>
                    <div style={{ display: 'flex' }}>
                      <AppUpload onFile={onAdd} fileNum={fileList.length}>
                        <Button type="primary" icon={<IconUpload />}>
                          {t['create.Attachments.upload']}
                        </Button>
                      </AppUpload>
                    </div>
                  </div>
                </Form.Item>
              </Col>
              <Col span={24}>
                <Space size={24} className={styles['create-button-group']}>
                  <Button
                    type="outline"
                    size="large"
                    onClick={() => onCancel()}
                  >
                    {t['cancel']}
                  </Button>
                  <Button
                    type="primary"
                    size="large"
                    onClick={onCreate}
                    loading={loading}
                    loadingFixedWidth
                  >
                    {record.id ? t['save'] : t['add']}
                  </Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </Modal>
    </div>
  );
}

export default CreateForm;
